import { program } from 'commander';
import colors from 'colors/safe';

import * as Enums from '../utils/Enums';
import Printer from '../utils/Printer';
import ExecuteHelper from '../utils/ExecuteHelper';
import ModulesHelper from '../utils/ModulesHelper';
import Modules from '../config/Modules';

interface InstallCommandOptions {
  type: string,
  module: string,
}

const install = (options: InstallCommandOptions) => {
  const { type, module } = options;
  if (!type || !module) {
    Printer.error('未指定 type 和/或 module', { type, module });
  }
  switch (type) {
    case Enums.ModuleType.App: installWebApp(options); break;
    case Enums.ModuleType.Service: installNodeService(options); break;
    default: break;
  }
};

export const installWebApp = (options: InstallCommandOptions) => {
  const { module } = options;
  if (Modules.isExternalApp(module)) {
    installExternalWebApp(options);
    return;
  }
  const { commandRunDirectory, webAppDirectory } = ModulesHelper.buildWebAppExecuteParams(module);
  ExecuteHelper.run('yarn', { cwd: webAppDirectory });
  ExecuteHelper.run('yarn', { cwd: commandRunDirectory });
};

const installExternalWebApp = (options: InstallCommandOptions) => {
  const { module } = options;
  const { commandRunDirectory } = ModulesHelper.buildExternalWebAppExecuteParams(module);
  ExecuteHelper.run(
    ModulesHelper.buildExternalWebAppYarnCommand(module, ''),
    { cwd: commandRunDirectory },
  );
};

export const installNodeService = (options: InstallCommandOptions) => {
  const { module } = options;
  const { commandRunDirectory } = ModulesHelper.buildNodeServiceExecuteParams(module);
  ExecuteHelper.run('yarn', { cwd: commandRunDirectory });
};

const moduleTypes = Object.values<string>(Enums.ModuleType);
const moduleTypesString = moduleTypes.map((type) => colors.green(type)).join('、');

export default program
  .command('install')
  .description('安装 app web server 或 node service 的依赖')
  .option('-t, --type [type]', `类型，可取值：${moduleTypesString}`)
  .option(
    '-m, --module [name]',
    `app 或 service 的名字，如 ${colors.green('userManagement')}、${colors.green('proxy')}`,
  )
  .action(install);
